from Common.BaseView import BaseView, Blueprint, Api, request
from Modules.sys_module.form import ModulePostForm, ModulePutForm, ModuleDeleteForm
from Modules.sys_module.form import ActionPostForm, ActionPutForm, ActionDeleteForm
from Modules.sys_module.model import db, ModuleModel, ActionModel
import copy

module_bp = Blueprint('module', __name__, url_prefix='/api')
api = Api(module_bp)


def create_tree(result, data):
    if not isinstance(data, dict):
        result = []
        return
    if data['pid'] is None:
        result.append(data)
        return
    for item in result:
        if item['id'] == data['pid']:
            if 'children' in item:
                item['children'].append(data)
            else:
                item['children'] = [data]
            return
        else:
            if 'children' in item:
                create_tree(item['children'], data)


class ModuleView(BaseView):
    default_action = [
        {'module_id': None, 'name': '查看', 'mark': '', 'api': '', 'method': 'GET', 'scope': ''},
        {'module_id': None, 'name': '修改', 'mark': '', 'api': '', 'method': 'PUT', 'scope': ''},
        {'module_id': None, 'name': '新增', 'mark': '', 'api': '', 'method': 'POST', 'scope': ''},
        {'module_id': None, 'name': '删除', 'mark': '', 'api': '', 'method': 'DELETE', 'scope': ''},
    ]

    def get(self):
        try:
            data = self.to_array(ModuleModel.query.all())
            result_array = []
            for item in data:
                create_tree(result_array, item)
            return self.result('0x00010', data=result_array)
        except Exception as error:
            return self.result('0x00011', data='%s' % error)

    def post(self):
        try:
            form = ModulePostForm()
            if form.validate_on_submit() is False:
                return self.result('0x00013')
            data_ins = ModuleModel(form.data)
            db.session.add(data_ins)
            db.session.commit()
            if data_ins.type == '分组':
                return self.result('0x00012')
            # 添加默认操作
            def_action = copy.deepcopy(self.default_action)
            action_list = []
            for item in def_action:
                item['module_id'] = data_ins.id
                if item['method'] == 'GET':
                    item['mark'] = data_ins.url.lstrip('/').replace('/', '.') + '.get'
                if item['method'] == 'PUT':
                    item['mark'] = data_ins.url.lstrip('/').replace('/', '.') + '.chg'
                if item['method'] == 'POST':
                    item['mark'] = data_ins.url.lstrip('/').replace('/', '.') + '.add'
                if item['method'] == 'DELETE':
                    item['mark'] = data_ins.url.lstrip('/').replace('/', '.') + '.del'
                item['api'] = data_ins.url
                action_list.append(ActionModel(item))
            data_ins.actions = action_list
            db.session.commit()
            return self.result('0x00012')
        except Exception as error:
            return self.result('0x00013', data='%s' % error)

    def put(self):
        try:
            form = ModulePutForm()
            if form.validate_on_submit() is False:
                return self.result('0x00016')
            new_data = form.data
            del new_data['id']
            del new_data['csrf_token']
            ModuleModel.query.filter_by(id=form.data['id']).update(new_data)
            db.session.commit()
            return self.result('0x00016')
        except Exception as error:
            print(error)
            return self.result('0x00017', data='%s' % error)

    def delete(self):
        try:
            form = ModuleDeleteForm()
            if form.validate_on_submit() is False:
                return self.result('0x00015')
            ModuleModel.query.filter_by(id=form.data['id']).delete()
            db.session.commit()
            return self.result('0x00014')
        except Exception as error:
            return self.result('0x00015', data='%s' % error)


class ActionView(BaseView):
    def get(self):
        try:
            module_id = request.args.get('module_id')
            if module_id is None:
                return self.result('0x00011')
            data_list = self.to_array(ActionModel.query.filter_by(module_id=module_id).all())
            return self.result('0x00010', data=data_list)
        except Exception as error:
            return self.result('0x00011', data='%s' % error)

    def post(self):
        try:
            form = ActionPostForm()
            if form.validate_on_submit() is False:
                return self.result('0x00013')
            data_ins = ActionModel(form.data)
            db.session.add(data_ins)
            db.session.commit()
            return self.result('0x00012')
        except Exception as error:
            return self.result('0x00013', data='%s' % error)

    def put(self):
        try:
            form = ActionPutForm()
            if form.validate_on_submit() is False:
                return self.result('0x00017')
            new_data = form.data
            del new_data['id']
            del new_data['csrf_token']
            ActionModel.query.filter_by(id=form.data['id']).update(new_data)
            db.session.commit()
            return self.result('0x00016')
        except Exception as error:
            return self.result('0x00017', data='%s' % error)

    def delete(self):
        try:
            form = ActionDeleteForm()
            if form.validate_on_submit() is False:
                return self.result('0x00015')
            ActionModel.query.filter_by(id=form.data['id']).delete()
            db.session.commit()
            return self.result('0x00014')
        except Exception as error:
            return self.result('0x00015', data='%s' % error)


api.add_resource(ModuleView, '/module')
api.add_resource(ActionView, '/module/action')
